//
//  NearbyViewController.m
//  微blog
//
//  Created by Jorn.Wu on 15/9/16.
//  Copyright (c) 2015年 Jorn.Wu(jorn_wza@sina.com). All rights reserved.
//

#import "NearbyViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "PoiModel.h"
#import "DataService.h"
#import "UIImageView+WebCache.h"

@interface NearbyViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation NearbyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    /**
     * 加载列表
     */
    [self loadTableView];
    
    /**
     * 定位
     */
    _locationManager = [[CLLocationManager alloc] init];
    if (kVersion >= 8.0) {  //ios 8.0 and later
        // 请求允许定位
        [_locationManager requestWhenInUseAuthorization];   //在使用程序的期间
    }
    
    //设置请求的准确度
    [_locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    _locationManager.delegate = self;
    //开始定位
    [_locationManager startUpdatingLocation];
    
    
//    测试（杭电）
//    [self loadNearbuPoisWithlLatitude:@"30.320278" longitude:@"120.338889"];
    
}


/**
 * 加载附近商圈列表
 */
- (void)loadTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    

    /**
     * 添加一个返回按钮，因为模态视图没有自动创建返回按钮
     */
    [self addNavigationThemeItemWithOrientation:@"left" title:nil image:@"button_back" action:@selector(backAction)];
   
    
}


/**
 * 返回
 */
- (void)backAction{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


/**
 * 通过当前所在的经纬度加载附近商圈
 */
- (void)loadNearbuPoisWithlLatitude:(NSString *)lat longitude:(NSString *)lon{
    
    // 01配置参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:lon forKey:@"long"];//经度
    [params setObject:lat forKey:@"lat"];//纬度
    [params setObject:@50 forKey:@"count"];
    
    // 02请求数据
    [DataService requestUrl:nearby_pois httpMethod:@"GET" params:params block:^(id result) {
        NSArray *pois = result[@"pois"];
        NSMutableArray *dataList = [NSMutableArray array];
        for (NSDictionary *dic in pois) {
            // 创建商圈模型对象
            PoiModel *poi = [[PoiModel alloc]initWithDataDic:dic];
            [dataList addObject:poi];
            
        }
        self.dataList = [dataList copy];
        [_tableView reloadData];
    }];
    
    
    
}

#pragma mark - CLLocationManagerDelegate
/**
 * 定位完成时调用
 */
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //停止定位
    [manager stopUpdatingLocation];
    
    //获取当前请求的位置
    CLLocation *location = [locations lastObject];
    //经纬度
    NSString *lon = [NSString stringWithFormat:@"%f",location.coordinate.longitude];//经度
    NSString *lat = [NSString stringWithFormat:@"%f",location.coordinate.latitude];//纬度
    
    /**
     * 加载网络数据
     */
    [self loadNearbuPoisWithlLatitude:lat longitude:lon];
    
    
}

#pragma mark - UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *locCellId = @"locCellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:locCellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:locCellId];
    }
    // 获取当前单元格对应的商圈对象
    PoiModel *poi = self.dataList[indexPath.row];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:poi.icon]];
    
    cell.textLabel.text = poi.title;
    return cell;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
